package cn.stylefeng.guns.sys.modular.system.controller;

import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.exception.AuthException;
import cn.stylefeng.guns.base.auth.exception.enums.AuthExceptionEnum;
import cn.stylefeng.guns.base.auth.service.AuthService;
import cn.stylefeng.guns.base.consts.ConstantsContext;
import cn.stylefeng.guns.sys.core.constant.cache.CacheKey;
import cn.stylefeng.guns.sys.core.exception.InvalidKaptchaException;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.Md5Util;
import cn.stylefeng.guns.sys.core.util.RedisUtils;
import cn.stylefeng.guns.sys.modular.system.entity.BtyWx;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.RoleIdEnum;
import cn.stylefeng.guns.sys.modular.system.entity.User;
import cn.stylefeng.guns.sys.modular.system.mapper.UserMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.UserAddParam;
import cn.stylefeng.guns.sys.modular.system.service.BtyWxService;
import cn.stylefeng.guns.sys.modular.system.service.RedisService;
import cn.stylefeng.guns.sys.modular.system.service.UserService;
import cn.stylefeng.roses.core.base.controller.BaseController;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.RequestEmptyException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.code.kaptcha.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 登录控制器
 *
 * @author fengshuonan
 * @Date 2017年1月10日 下午8:25:24
 */
@Controller
public class LoginController extends BaseController {

    @Autowired
    private AuthService authService;

    @Autowired
    private UserService userService;
    @Resource
    private BtyWxService wxService;
    @Resource
    private RedisService redisService;

    /**
     * 跳转到主页
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/", method = RequestMethod.GET)
    public String index(Model model, @RequestParam(required = false)Integer version,HttpServletRequest request) throws Exception {

        if(version==null){
            version=2;
        }
        //判断用户是否登录
        if (LoginContextHolder.getContext().hasLogin()) {
            Map<String, Object> userIndexInfo = userService.getUserIndexInfo(version);

            //用户信息为空，提示账号没分配角色登录不进去
            if (userIndexInfo == null) {
                model.addAttribute("tips", "该用户没有角色，无法登陆");
                return "/login.html";
            } else {
                model.addAllAttributes(userIndexInfo);
                return "/index.html";
            }

        } else {
            //获取微信公众平台code
            String coco=request.getParameter("coco");
            //获取微信开放平台code
            String code = request.getParameter("code");
            System.out.println("code:" + code);
            if (ToolUtil.isNotEmpty(code)) {
            //微信开放平台通过code获取unionid
            RestTemplate restTemplate = new RestTemplate();
            String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx64beda25e2fd5af9&secret=0a3b656f855941b4f31be735dfc1ed4f&code=" + code + "&grant_type=authorization_code";
            String content = restTemplate.getForObject(url, String.class);
            JSONObject jsonObject = JSONObject.parseObject(content);
            String unionid = jsonObject.get("unionid")==null?"":jsonObject.get("unionid").toString();

            BtyWx wx = wxService.getOne(new QueryWrapper<BtyWx>().eq("unionid", unionid));
            if (ToolUtil.isNotEmpty(wx)) {
                String phone = wx.getPhone();
                //通过电话获取用户信息
                List<User> list = userService.getUserByphone(phone);
                if (list.size() > 0) {
                    String userName = list.get(0).getAccount();
                    ewmLogin(userName);
                }else{
                    model.addAttribute("tips", "<span>未获取到用户信息,请注册账号</span>");
                    return "/login.html";
                }
            } else {
                model.addAttribute("tips", "<span>请选择<text>“其他登录”</text>'扫码关注'<text>“半天妖办公平台公众号”</text>，在公众号的<text>“微服务”</text>中进行微信绑定</span>");
                return "/login.html";
            }
                return REDIRECT + "/";
         }else if(ToolUtil.isNotEmpty(coco)){
                //微信公众平台通过code获取openid
                RestTemplate restTemplate = new RestTemplate();
                String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx373650bf8de7f27d&secret=d3e9c259a6dbca1c5ef73beb1804f3c7&code=" + coco + "&grant_type=authorization_code";
                String content = restTemplate.getForObject(url, String.class);
                JSONObject jsonObject = JSONObject.parseObject(content);
                String openid = jsonObject.get("openid")==null?"":jsonObject.get("openid").toString();

                BtyWx wx = wxService.getOne(new QueryWrapper<BtyWx>().eq("openid", openid));
                if (ToolUtil.isNotEmpty(wx)) {
                    String phone = wx.getPhone();
                    //通过电话获取用户信息
                    List<User> list = userService.getUserByphone(phone);
                    if (list.size() > 0) {
                        String userName = list.get(0).getAccount();
                        ewmLogin(userName);
                    }else{
                        //model.addAttribute("tips", "获取不到用户信息,请确认手机号是否一致");
                        return "/login.html";
                    }
                } else {
                    return "/login.html";
                }
                return REDIRECT + "/";
            }else{
                return "/login.html";
            }

        }
    }
    /**
     * 点击二维码登录执行的动作
     * @author
     */
    @RequestMapping(value = "/ewmLogin",method = RequestMethod.POST)
    @ResponseBody
    public ResponseData ewmLogin(String userName){
        String token = authService.login(userName);
        getSession().setAttribute("token", token);
        //生成业务系统token
        redisService.saveRedis(CacheKey.YWXTTOKENMAP,token,userName);
        return new SuccessResponseData(token);
    }

    /**
     * 跳转到登录页面
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:41 PM
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        if (LoginContextHolder.getContext().hasLogin()) {
            return REDIRECT + "/";
        } else {
            return "/login.html";
        }
    }

    /**
     * 点击登录执行的动作
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:42 PM
     */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData loginVali() throws Exception {
        String username = super.getPara("username");
        String password = super.getPara("password");
        String remember = super.getPara("remember");

        if (ToolUtil.isOneEmpty(username, password)) {
            throw new RequestEmptyException("账号或密码为空！");
        }

        //验证验证码是否正确
        if (ConstantsContext.getKaptchaOpen()) {
            String kaptcha = super.getPara("kaptcha").trim();
            String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
            if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
                throw new InvalidKaptchaException();
            }
        }

        //登录并创建token
        String token = authService.login(username, password);


        //生成业务系统token
        redisService.saveRedis(CacheKey.YWXTTOKENMAP,token,username);
        getSession().setAttribute("token",token);
        return new SuccessResponseData(token);
    }

    /**
     * 退出登录
     *
     * @author fengshuonan
     * @Date 2018/12/23 5:42 PM
     */
    @RequestMapping(value = "/logout")
    @ResponseBody
    public ResponseData logOut() {
        authService.logout();
        return new SuccessResponseData();
    }

    /**
     * 跳转到注册页面
     *
     * @author jiangge
     * @Date 2020/10/13 9:41 AM
     */
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public String register() {
        return  "/register.html";
    }

    @ResponseBody
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ResponseData register(HttpServletRequest request, HttpServletResponse response) {

        String account = super.getPara("account");
        String name = super.getPara("name");
        String password = super.getPara("password");
        String confirmPassword = super.getPara("confirmPassword");
        String phone = super.getPara("phone");
        String roleIds = super.getPara("roleIds");

        UserAddParam userAddParam=new UserAddParam();
        userAddParam.setAccount(account);
        userAddParam.setName(name);
        userAddParam.setPassword(password);
        userAddParam.setConfirmPassword(confirmPassword);
        userAddParam.setPhone(phone);
        //角色名称赋值
        userAddParam.setRoleIds(RoleIdEnum.getByCode(Long.valueOf(roleIds)).getMessage());
        ResponseData responseData = this.userService.addUserAndSetRole(userAddParam);
        return responseData;
    }

}